from django import http
from django.shortcuts import render
from django.views import View
# from apps.verification.constants import IMAGE_CODE_EXPIRE_TIME, SMS_CODE_EXPIRE_TIME, SMS_CODE_FLAG_TIME
from celery_tasks.sms.tasks import send_sms_code

from utils.response_code import RETCODE
from django_redis import get_redis_connection


class ImageCodeView(View):
    def get(self, request, uuid):
        from libs.captcha.captcha import captcha
        code, image = captcha.generate_captcha()
        conn = get_redis_connection('code')
        conn.setex('img:%s' % uuid, 60 * 60, code)
        return http.HttpResponse(image, content_type='image/jpeg')


import logging

logger = logging.getLogger('django')


class SmsCodeView(View):
    def get(self, request, mobile):
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        if not all([image_code, uuid]):
            return http.HttpResponseBadRequest('参数不全')
        try:
            conn = get_redis_connection('code')
            redis_code = conn.get('img:%s' % uuid)
            if redis_code is None:
                return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图片验证码错误'})
            if redis_code.decode().lower() != image_code.lower():
                return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图片验证码错误'})
            conn.delete('img:%s' % uuid)
            send_flag = conn.get('send_flag:%s' % mobile)
            if send_flag:
                return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '哥们,你操作太频繁了,嫂子会不高兴的'})
        except Exception as e:
            logger.error(e)
            return http.HttpResponseBadRequest('redis数据库连接错误')
        from random import randint
        sms_code = '%06d' % randint(0, 999999)
        # print(sms_code)
        # conn.setex('sms:%s' % mobile, 300, sms_code)
        # conn.setex('send_flag:%s' % mobile, 300, 1)
        pl = conn.pipeline()
        pl.setex('sms:%s' % mobile, 300, sms_code)
        pl.setex('send_flag:%s' % mobile, 300, 1)
        pl.execute()
        send_sms_code.delay(mobile, sms_code)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})


class CheckSmsCodeView(View):
    def get(self, request):
        mobile = request.GET.get('mobile')
        sms_code = request.GET.get('sms_code')
        conn = get_redis_connection('code')
        redis_code = conn.get('sms:%s' % mobile)
        if redis_code.decode() != sms_code:
            return http.JsonResponse({'code': RETCODE.SMSCODERR, 'errmsg': '短信验证码错误'})
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
        # 失去光标的时候检测短信验证码是否正确
